#include "usermanagementpanel.h"
#include <QTableWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QHeaderView>
#include <QMessageBox>
#include <QInputDialog>
#include <QFormLayout> // For edit/add dialog
#include <QDialog>
#include <QLineEdit>
#include <QComboBox>
#include <QDialogButtonBox>

// C backend interface
extern "C" {
#include "../backend/user.h"
}

UserManagementPanel::UserManagementPanel(QWidget *parent) : QWidget(parent)
{
    setupUi();
    loadUsers(); // Load users initially
}

UserManagementPanel::~UserManagementPanel()
{
    freeUserList(); // Free the C linked list when the panel is destroyed
}

void UserManagementPanel::setupUi()
{
    // Table View
    userTable = new QTableWidget();
    userTable->setColumnCount(5); // ID, Name, Type, Address, Phone
    userTable->setHorizontalHeaderLabels(QStringList() << "ID" << "用户名" << "类型" << "地址" << "电话");
    userTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    userTable->setSelectionBehavior(QAbstractItemView::SelectRows); // Select whole rows
    userTable->setSelectionMode(QAbstractItemView::SingleSelection); // Only one row at a time
    userTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // Don't allow direct editing in table

    // Buttons
    btnAdd = new QPushButton("➕ 添加用户");
    btnEdit = new QPushButton("✏️ 编辑用户");
    btnDelete = new QPushButton("❌ 删除用户");
    btnRefresh = new QPushButton("🔄 刷新列表");

    // User Count Label
    lblUserCount = new QLabel("总用户数：0");

    // Layouts
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(btnAdd);
    buttonLayout->addWidget(btnEdit);
    buttonLayout->addWidget(btnDelete);
    buttonLayout->addStretch();
    buttonLayout->addWidget(btnRefresh);

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(userTable);
    mainLayout->addWidget(lblUserCount, 0, Qt::AlignRight);

    // Connections
    connect(btnRefresh, &QPushButton::clicked, this, &UserManagementPanel::loadUsers);
    connect(btnAdd, &QPushButton::clicked, this, &UserManagementPanel::addUser);
    connect(btnEdit, &QPushButton::clicked, this, &UserManagementPanel::editUser);
    connect(btnDelete, &QPushButton::clicked, this, &UserManagementPanel::deleteUser);
    // Connect double click on table row to edit action
    connect(userTable, &QTableWidget::itemDoubleClicked, this, &UserManagementPanel::editUser);
}

void UserManagementPanel::loadUsers()
{
    freeUserList(); // Free previous list before loading new one
    int count = load_users("users.dat", &userListHead); // Pass only filename
    lblUserCount->setText(QString("总用户数：%1").arg(count));
    populateTable();
}

void UserManagementPanel::populateTable()
{
    clearTable();
    userTable->setRowCount(0); // Clear existing rows first

    UserNode* current = userListHead;
    int row = 0;
    while (current != nullptr) {
        userTable->insertRow(row);
        userTable->setItem(row, 0, new QTableWidgetItem(QString::number(current->data.id)));
        userTable->setItem(row, 1, new QTableWidgetItem(QString::fromUtf8(current->data.name)));
        userTable->setItem(row, 2, new QTableWidgetItem(current->data.type == USER_TYPE_ADMIN ? "管理员" : "普通用户"));
        userTable->setItem(row, 3, new QTableWidgetItem(QString::fromUtf8(current->data.address)));
        userTable->setItem(row, 4, new QTableWidgetItem(QString::fromUtf8(current->data.phone)));
        // Store user ID in the first column's item data for easy retrieval
        userTable->item(row, 0)->setData(Qt::UserRole, current->data.id);
        current = current->next;
        row++;
    }
}

void UserManagementPanel::clearTable()
{
    userTable->clearContents();
    userTable->setRowCount(0);
}

void UserManagementPanel::freeUserList()
{
    if (userListHead) {
        free_all_users(userListHead);
        userListHead = nullptr;
    }
}

// --- Dialog for Adding/Editing Users ---
class UserDialog : public QDialog {
public:
    QLineEdit *editId; // Read-only for edit, editable for add
    QLineEdit *editName;
    QLineEdit *editPassword;
    QLineEdit *editAddress;
    QLineEdit *editPhone;
    QComboBox *comboType;
    bool isEditMode;
    int originalId; // Store original ID for editing

    UserDialog(const User* userData = nullptr, QWidget *parent = nullptr)
        : QDialog(parent), isEditMode(userData != nullptr), originalId(userData ? userData->id : -1)
    {
        setWindowTitle(isEditMode ? "编辑用户" : "添加用户");
        QFormLayout *formLayout = new QFormLayout(this);

        editId = new QLineEdit();
        editName = new QLineEdit();
        editPassword = new QLineEdit();
        editPassword->setEchoMode(QLineEdit::Password); // Hide password
        editAddress = new QLineEdit();
        editPhone = new QLineEdit();
        comboType = new QComboBox();
        comboType->addItem("普通用户", USER_TYPE_NORMAL);
        comboType->addItem("管理员", USER_TYPE_ADMIN);

        formLayout->addRow("ID:", editId);
        formLayout->addRow("用户名:", editName);
        formLayout->addRow("密码:", editPassword);
        formLayout->addRow("地址:", editAddress);
        formLayout->addRow("电话:", editPhone);
        formLayout->addRow("类型:", comboType);

        if (isEditMode) { // Editing existing user
            editId->setText(QString::number(userData->id));
            editId->setReadOnly(true); // ID cannot be changed
            editName->setText(QString::fromUtf8(userData->name));
            editPassword->setPlaceholderText("留空则不修改密码"); // Password field is empty for editing
            editAddress->setText(QString::fromUtf8(userData->address));
            editPhone->setText(QString::fromUtf8(userData->phone));
            comboType->setCurrentIndex(userData->type == USER_TYPE_ADMIN ? 1 : 0);
        } else { // Adding new user
            editId->setPlaceholderText("自动生成或手动输入");
            editId->setReadOnly(false); // Allow setting ID for new user
            // Find the next available ID (simple approach)
            UserNode* head = nullptr;
            int count = load_users("users.dat", &head); // Pass only filename
            int nextId = 1;
            if (head) {
                UserNode* p = head;
                while(p) {
                    if (p->data.id >= nextId) nextId = p->data.id + 1;
                    p = p->next;
                }
                free_all_users(head);
            }
            editId->setText(QString::number(nextId));
        }

        QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
        formLayout->addRow(buttonBox);
        connect(buttonBox, &QDialogButtonBox::accepted, this, &UserDialog::accept);
        connect(buttonBox, &QDialogButtonBox::rejected, this, &UserDialog::reject);
    }

    User getUserData(const User* originalUserData = nullptr) const {
        User user;
        user.id = editId->text().toInt();
        strncpy(user.name, editName->text().toUtf8().constData(), sizeof(user.name) - 1);
        user.name[sizeof(user.name) - 1] = '\0';

        QString newPassword = editPassword->text();
        if (isEditMode && newPassword.isEmpty() && originalUserData) {
            // If editing and password field is empty, keep the original password
            strncpy(user.password, originalUserData->password, sizeof(user.password) - 1);
        } else {
            strncpy(user.password, newPassword.toUtf8().constData(), sizeof(user.password) - 1);
        }
        user.password[sizeof(user.password) - 1] = '\0';

        strncpy(user.address, editAddress->text().toUtf8().constData(), sizeof(user.address) - 1);
        user.address[sizeof(user.address) - 1] = '\0';
        strncpy(user.phone, editPhone->text().toUtf8().constData(), sizeof(user.phone) - 1);
        user.phone[sizeof(user.phone) - 1] = '\0';
        user.type = comboType->currentData().toInt();
        return user;
    }
};
// --- End Dialog ---


void UserManagementPanel::addUser()
{
    UserDialog dialog(nullptr, this); // Pass nullptr for add mode
    if (dialog.exec() == QDialog::Accepted) {
        User newUser = dialog.getUserData();

        // Basic validation
        if (strlen(newUser.name) == 0 || strlen(newUser.password) == 0) {
             QMessageBox::warning(this, "错误", "用户名和密码不能为空！");
             return;
        }
        if (newUser.id <= 0) {
             QMessageBox::warning(this, "错误", "用户ID必须为正整数！");
             return;
        }

        // Reload list to ensure we have the latest data before adding
        freeUserList();
        load_users("users.dat", &userListHead); // Pass only filename

        // Check if ID already exists
        if (find_user_by_id(userListHead, newUser.id)) {
             QMessageBox::warning(this, "错误", QString("用户ID %1 已存在！").arg(newUser.id));
             freeUserList(); // Free list after check
             return;
        }
         // Check if Name already exists
         UserNode* p = userListHead;
         while(p) {
             if (strcmp(p->data.name, newUser.name) == 0) {
                 QMessageBox::warning(this, "错误", QString("用户名 '%1' 已存在！").arg(QString::fromUtf8(newUser.name)));
                 freeUserList(); // Free list after check
                 return;
             }
             p = p->next;
         }

        // Add user to the list in memory
        if (add_user(&userListHead, &newUser)) {
            // Save the updated list back to file
            if (save_users("users.dat", userListHead)) { // Pass only filename
                QMessageBox::information(this, "成功", QString("用户 '%1' 添加成功！").arg(QString::fromUtf8(newUser.name)));
                loadUsers(); // Reload table to show the new user
            } else {
                QMessageBox::critical(this, "错误", "保存用户数据失败！");
                // Attempt to remove the user from memory list if save failed? Or handle differently.
                // For now, just reload to reflect the state before the failed save.
                loadUsers();
            }
        } else {
            QMessageBox::critical(this, "错误", "添加用户到内存失败！");
            // No need to save if add failed, just reload
            loadUsers();
        }
    }
     // Ensure list is freed if dialog was cancelled or add failed early
     // freeUserList(); // Already freed in loadUsers or after checks
}

void UserManagementPanel::editUser()
{
    QList<QTableWidgetItem*> selectedItems = userTable->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要编辑的用户！");
        return;
    }

    int selectedRow = selectedItems.first()->row();
    int userId = userTable->item(selectedRow, 0)->data(Qt::UserRole).toInt();

    // Find the user data in our loaded list
    UserNode* userNode = find_user_by_id(userListHead, userId);
    if (!userNode) {
        QMessageBox::critical(this, "错误", "无法在内存中找到所选用户！请刷新列表。");
        return;
    }

    UserDialog dialog(&userNode->data, this); // Pass user data for edit mode
    if (dialog.exec() == QDialog::Accepted) {
        User updatedUser = dialog.getUserData(&userNode->data); // Pass original data to handle password

         // Basic validation
        if (strlen(updatedUser.name) == 0) {
             QMessageBox::warning(this, "错误", "用户名不能为空！");
             return;
        }
         // Check if new Name conflicts with others (excluding self)
         UserNode* p = userListHead;
         while(p) {
             if (p->data.id != updatedUser.id && strcmp(p->data.name, updatedUser.name) == 0) {
                 QMessageBox::warning(this, "错误", QString("用户名 '%1' 已被其他用户使用！").arg(QString::fromUtf8(updatedUser.name)));
                 return;
             }
             p = p->next;
         }


        // Update user in the list in memory
        if (update_user(userListHead, &updatedUser)) {
            // Save the updated list back to file
            if (save_users("users.dat", userListHead)) { // Pass only filename
                QMessageBox::information(this, "成功", QString("用户 '%1' 更新成功！").arg(QString::fromUtf8(updatedUser.name)));
                loadUsers(); // Reload table to show the updated user
            } else {
                QMessageBox::critical(this, "错误", "保存用户数据失败！");
                loadUsers(); // Reload to reflect state before failed save
            }
        } else {
             QMessageBox::critical(this, "错误", "更新用户内存数据失败！");
             loadUsers(); // Reload
        }
    }
}

void UserManagementPanel::deleteUser()
{
    QList<QTableWidgetItem*> selectedItems = userTable->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要删除的用户！");
        return;
    }

    int selectedRow = selectedItems.first()->row();
    int userId = userTable->item(selectedRow, 0)->data(Qt::UserRole).toInt();
    QString userName = userTable->item(selectedRow, 1)->text();

    // Confirmation dialog
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除", QString("确定要删除用户 '%1' (ID: %2) 吗？此操作不可恢复！").arg(userName).arg(userId),
                                QMessageBox::Yes|QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        // Delete user from the list in memory
        if (delete_user(&userListHead, userId)) {
            // Save the updated list back to file
            if (save_users("users.dat", userListHead)) { // Pass only filename
                QMessageBox::information(this, "成功", QString("用户 '%1' 删除成功！").arg(userName));
                loadUsers(); // Reload table to reflect deletion
            } else {
                QMessageBox::critical(this, "错误", "保存用户数据失败！");
                loadUsers(); // Reload to reflect state before failed save
            }
        } else {
             QMessageBox::critical(this, "错误", "删除用户内存数据失败！");
             loadUsers(); // Reload
        }
    }
}
